package com.sinopec.basemodule.common

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import androidx.appcompat.app.AppCompatActivity
import com.sinopec.basemodule.R
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.BasePresenter
import com.sinopec.basemodule.base.CustomToolbar
import kotlinx.android.synthetic.main.activity_common_veb_view.*

/**
 * 通用网页
 */
class CommonVebViewActivity : BaseActivity<BasePresenter>() {

    companion object {
        @JvmStatic
        fun startActivity(appCompatActivity: AppCompatActivity, url: String, title: String) {
            val intent = Intent(appCompatActivity, CommonVebViewActivity::class.java)
            val b = Bundle()
            b.putString("url", url)
            b.putString("title", title)
            intent.putExtras(b)
            appCompatActivity.startActivity(intent)
        }

    }

    /**
     * web url
     */
    private val mUrl by lazy {
        intent.getStringExtra("url") ?: "https://www.yeloworld.cn/"
    }

    /**
     * 标题
     */
    private val mTitle by lazy {
        intent.getStringExtra("title") ?: ""
    }

    override fun getContentView(): Int {
        return R.layout.activity_common_veb_view
    }

    override fun configToolbar(rToolbar: CustomToolbar) {
        rToolbar.setTitle(mTitle)
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView(savedInstanceState: Bundle?) {
        webview.isVerticalScrollBarEnabled = false //垂直滚动不显示

        val settings: WebSettings = webview.settings
        settings.setSupportZoom(true)
        //设置支持js
        settings.javaScriptEnabled = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        settings.databaseEnabled = true
        settings.allowFileAccess = true
        settings.allowContentAccess = true
        //webview.loadUrl("https://www.baidu.com/")
        webview.loadUrl(mUrl)
        webview.webViewClient = object :WebViewClient(){
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }


        webview.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                if (newProgress == 100) {
                    progressBar.visibility = View.GONE //加载完网页进度条消失
                } else {
                    progressBar.visibility = View.VISIBLE //开始加载网页时显示进度条
                    progressBar.progress = newProgress //设置进度值
                }
            }
        }
    }
}